package com.gs.common.util;

import cn.hutool.core.util.ObjectUtil;
import com.gs.entity.OssFile;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @title: 孙杨申
 * @date 2022/1/31 21:34
 */
@Component
@Data
public class MinIOUtil {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Resource
    private MinioClient minioClient;

    /**
     * 查看存储bucket是否存在
     * @param bucketName 存储bucket
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean createBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除文件
     * @param bucketName 存储bucket名称
     * @param objectName 文件名
     * @return Boolean
     */
    public Boolean removeObject(String bucketName, String objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 文件上传
     * @param file 文件
     * @param bucketName 存储bucket
     * @param fileName 文件名
     * @return Boolean
     */
    public Boolean upload(MultipartFile file, String bucketName, String path, String fileName) {
        try {
            if(ObjectUtil.isEmpty(path)) path = "";

            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(path + fileName)
                    .stream(file.getInputStream(),file.getSize(),-1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }



    /**
     *
     * @param bucketName 桶名称
     * @param url url
     * @return
     * @throws ServerException
     * @throws InsufficientDataException
     * @throws ErrorResponseException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws InvalidResponseException
     * @throws XmlParserException
     * @throws InternalException
     */
    public InputStream getObject(String bucketName, String url) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
                .object(url).build();
        InputStream response = minioClient.getObject(objectArgs);
        return response;
    }

    public InputStream getObject(String url) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return getObject(bucketName, url);
    }

    /**
     * 文件下载
     * @param bucketName 存储bucket名称
     * @param url 文件路径
     * @param res response
     * @return Boolean
     */
    public void download(String bucketName, String url, HttpServletResponse res) {

        try (InputStream response = getObject(bucketName, url)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                //设置强制下载不打开
                res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + url.substring(url.lastIndexOf("/") + 1, url.length()));
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看文件对象
     * @param bucketName 存储bucket名称
     * @param path 路径
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects(String bucketName, String path) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).prefix(path).build());

        List<Item> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                objectItems.add(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectItems;
    }

    /**
     * 批量删除文件对象
     * @param bucketName 存储bucket名称
     * @param objects 对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }


    /**
     * 将oss的对象转换成系统的OssFile对象
     * @param items 
     * @return
     */
    public static List<OssFile> convertOssFileList(List<Item> items) {
        List<OssFile> resultList = new ArrayList<>();

        items.forEach(item -> {
            String objectName = item.objectName();
            boolean dir = item.isDir();
            long size = 0;
            ZonedDateTime zonedDateTime = null;

            if(!dir) {
                size = item.size();
                zonedDateTime = item.lastModified();
            }

            OssFile ossFile = new OssFile();
            ossFile.setFileName(objectName);
            ossFile.setDir(dir);
            ossFile.setSize(size);
            if(ObjectUtil.isNotEmpty(zonedDateTime)) {
                ossFile.setLastModified(zonedDateTime.toLocalDateTime());
            }
            resultList.add(ossFile);

        });
        return resultList;
    }

    /**
     * 获取minio的下载路径
     * @param bucketName bucketName
     * @param path 文件路径
     * @param expireTime 过期时间
     * @return
     */
    public String getDownloadURL(String bucketName, String path, Integer expireTime) {
//        Map<String, String> reqParams = new HashMap<>();
//        reqParams.put("response-content-type", "application/json");
//        String policy = "{\n" +
//                "    \"Version\": \"2012-10-17\",\n" +
//                "    \"Statement\": [\n" +
//                "        {\n" +
//                "            \"Effect\": \"Allow\",\n" +
//                "            \"Action\": [\n" +
//                "                \"s3:GetObject\"\n" +
//                "            ],\n" +
//                "            \"Resource\": [\n" +
//                "                \"arn:aws:s3:::*\"\n" +
//                "            ]\n" +
//                "        }\n" +
//                "    ]\n" +
//                "}";
        try {

            //durationSeconds表示多久过期，默认3600秒，如果是小于3600，会被设置成默认值。
//            AssumeRoleProvider provider = new AssumeRoleProvider(
//                    endpoint, "wallper", "wallper1241913781", 3600, policy
//                    , null, null, "roleSessionName", null, null
//            );
//            Credentials credentials = provider.fetch();
//            System.out.println("accessKey:" + credentials.accessKey());
//            System.out.println("secretKey:" + credentials.secretKey());
//            System.out.println("sessionToken:" + credentials.sessionToken());
//
//            System.out.println(credentials.isExpired());
//            System.out.println("Credentials ok");


            //正常情况下，会将上面临时生成的accessKey，secretKey，sessionToken返给前端，让前端上传。
            //使用临时的provider创建minioclient
//            StaticProvider staticProvider = new StaticProvider(credentials.accessKey(), credentials.secretKey(), credentials.sessionToken());
            // wallper wallper1241913781

//            MinioClient minioClient2 = MinioClient.builder().endpoint(endpoint).credentialsProvider(staticProvider).build();


            String product = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET) // GET是文件访问地址, 上传用post
                            .bucket(bucketName)
                            .object(path)
                            .expiry(expireTime)
//                            .extraQueryParams(reqParams)
                            .build());
            return product;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载文件地址
     * @param bucketName
     * @param path
     * @return
     */
    public String getDownloadURL(String bucketName, String path) {
        return getDownloadURL(bucketName, path, 60 * 60 * 24);
    }
}
//————————————————
//        版权声明：本文为CSDN博主「冰红茶不会渴」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/weixin_43241706/article/details/115351137